package com.ikun.service.impl;

import com.ikun.mapper.BusinessMapper;
import com.ikun.mapper.OrderMapper;
import com.ikun.mapper.ShoppingCartMapper;
import com.ikun.pojo.Business;
import com.ikun.pojo.Order;
import com.ikun.pojo.ShoppingCart;
import com.ikun.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
@Autowired
 private OrderMapper orderMapper;
@Autowired
 private ShoppingCartMapper shoppingCartMapper;
@Autowired
private BusinessMapper businessMapper;
    @Override
    public List<Order> getAllOrder(Integer userId) {
        return orderMapper.getAllOrder(userId);
    }

    @Override
    public Order getOrderById(Integer id) {
        return orderMapper.getOrderById(id);
    }

    @Override
    public List<Business> getBusinessByUserIdAndTypeId(Integer userId, Integer typeId) {
        List<Business> businesses=null;
        List<Order> orders=orderMapper.getOrderByUserId(userId);
        for(Order o:orders){
            Business b=businessMapper.getBusinessById(o.getBusinessId());
            if(b.getStoreClassId()==typeId){
                businesses.add(b);
            }
        }
        return businesses;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addOrder(Integer userId, Integer businessId, Float price, String shippingAddress) {
        //业务1.根据Integer userId, Integer userId, Float price, String shippingAddress插入订单
        Order order=new Order();
        order.setUserId(userId);
        order.setBusinessId(businessId);
        order.setPrice(price);
        order.setShippingAddress(shippingAddress);
        orderMapper.addOrder(order);
        Integer orderId=order.getOrderId();//获得订单的自增主键为
        //业务2.根据userId，businessId在购物车中查询该订单对应的菜品，需要知道菜品id以及对应的数量
        List<ShoppingCart>dishesList=shoppingCartMapper.getShoppingCartIdByBusinessIdAndUserId(userId, businessId);

        //业务3.然后将查询到的菜品信息放入订单菜品表
        dishesList.forEach((dish) ->{
            orderMapper.addOrderDishes(orderId, dish.getDishesId(), dish.getQuantity());//向订单菜品表中添加数据
            shoppingCartMapper.deleteShoppingCartByUserIdAndBusinessIdAndDishesId(userId, businessId,dish.getDishesId());//将刚刚用过的购物车中的菜品删除
        });
        return orderId;

    }
//根据用户id查询订单表中的对应的商家信息
    public Map<Integer,Object>getOrderBusinessInfo(Integer userId){
        List<Order>listOrder=orderMapper.getOrderByUserId(userId);
        Map<Integer,Object> map=new HashMap<>();
        listOrder.forEach(
                (order) -> {
                    Business business=businessMapper.getBusinessById(order.getBusinessId());
                   //将order.getOrderId的值作为Map<Integer,Object>里面的Integer,business对应Map<Integer,Object>里面的Object
                    map.put(order.getOrderId(),business);


                }
        );
        return map;
    }
    //根据orderId修改order_status
    @Override
    public int updateOrderStatus(Integer orderId, Integer orderStatus) {
        return orderMapper.updateOrderStatus(orderId,orderStatus);
    }
    //获取买过的商家
    public List<Business> getBuyBusiness(Integer userId){
        List<Order>listOrder=orderMapper.getOrderByUserId(userId);
        List<Business> listBusiness=new ArrayList<>();
        for(Order order:listOrder){
            Business business=businessMapper.getBusinessById(order.getBusinessId());
            listBusiness.add(business);
        }
        // 去重
        List<Business> uniqueListBusiness = listBusiness.stream()
                .collect(Collectors.toMap(
                        Business::getBusinessId, // key映射函数
                        Function.identity(),     // value映射函数
                        (existing, replacement) -> existing // 合并函数，如果有重复的key，保留现有的
                ))
                .values()
                .stream()
                .toList();
        return uniqueListBusiness;
    }

    /**
     *
     * 根据userId查询其所有订单的详情
     * @param userId
     * @return
     */
    @Override
    public Map<Integer, Object> getOrderDishesDescriptionByUserId(Integer userId) {
        //1.查询用户的所有订单
        List<Order> listOrder=orderMapper.getOrderByUserId(userId);
        //2.根据上面的订单的id查询对应的菜品详情:菜品的id,菜品的名称,菜品的数量,菜品的图片
        Map<Integer,Object> map=new HashMap<>();
        listOrder.forEach(
                (order) -> {
                    //1.查询该orderId对应的菜品
                    List<Map<String,Object>> listDishes=orderMapper.getOrderDishesDescriptionByOrderId(order.getOrderId());
                    //2.将order.getOrderId的值作为Map<Integer,Object>里面的Integer,listDishes对应Map<Integer,Object>里面的Object
                    map.put(order.getOrderId(),listDishes);
                }
        );
        return map;
    }


}
